<?php
/*
	微信会员卡
*/
defined('BY_JYA') or exit('error');
$_RQ['op']=$_RQ['op']?$_RQ['op']:'edit';
$return=array();
$tabs=array(
	array('op'=>'edit','title'=>'会员卡详情设置'),
	array('op'=>'setting','title'=>'会员卡激活设置'),
	array('op'=>'change','title'=>'修改库存'),
	array('op'=>'del','title'=>'删除会员卡'),
);
set_html('tabs',$tabs);
if($_RQ['op']=='setting'){
	if($_RQ['postdata']){
		$post=get_postdata();
		uni_setting('wx_card_setting',$post);
		exi('设置成功！');
	}
	$return['item']=uni_setting('wx_card_setting');
	$return['htmls']=array(
		'type'=>'edit',
		'edit_tab'=>true,
		'edits'=>array(
			array('title'=>'基本信息','list'=>array(
				array('type'=>'switch','name'=>'open','title'=>'会员卡领取','help'=>'设置会员中心是否可以领取微信会员卡'),
				array('type'=>'switch','name'=>'active','title'=>'会员卡激活','help'=>'激活会员卡时是否需要填写激活信息,不需求则自动激活会员卡！'),
				array('type'=>'switch','name'=>'realname','title'=>'真实姓名','show'=>array('active'=>1),'help'=>'设置激活时是否需要填写真实姓名'),
				array('type'=>'switch','name'=>'mobile','title'=>'手机号','show'=>array('active'=>1),'help'=>'设置激活时是否需要填写手机号'),
				array('type'=>'switch','name'=>'mobile_code','title'=>'短信验证','show'=>array('active'=>1),'help'=>'设置激活时是否需要填写短信验证码'),
				array('type'=>'switch','name'=>'mobile_code_temp','title'=>'验证短信模版','show'=>array('active'=>1,'mobile_code'=>1),'help'=>'设置验证码短信模版ID'),
			)),
			array('title'=>'激活赠送','list'=>array(
				array('type'=>'string','name'=>'give_credit2','title'=>'赠送余额','help'=>'用户激活后赠送余额，如果为空或者0则不赠送'),
				array('type'=>'string','name'=>'give_credit1','title'=>'赠送积分','help'=>'用户激活后赠送积分，如果为空或者0则不赠送'),
				
			)),
		),
	);
	exi($return);
}
if($_RQ['op']=='edit'){
	$return['name_types']=array(
		'FIELD_NAME_TYPE_LEVEL'=>'等级',
		'FIELD_NAME_TYPE_COUPON'=>'优惠券',
		'FIELD_NAME_TYPE_STAMP'=>'印花',
		'FIELD_NAME_TYPE_DISCOUNT'=>'折扣',
		'FIELD_NAME_TYPE_ACHIEVEMEN'=>'成就',
		'FIELD_NAME_TYPE_MILEAGE'=>'里程',
		'FIELD_NAME_TYPE_SET_POINTS'=>'集点',
		'FIELD_NAME_TYPE_TIMS'=>'次数',
	);
	if($_RQ['postdata']){
		$post=get_postdata();
		if(count($post['custom_field'])>3){
			exi('自定义类别最多添加三个！','error');
		}
		if(!$post['logo_url']){
				exi('请先设置logo！','error');
		}
		if(!$post['background_pic_url']){
				exi('请先设置背景图片！','error');
		}
		if(!$post['prerogative']){
				exi('请先设置特权说明！','error');
		}
		if($post['supply_bonus'] && !$post['bonus_rules']){
				exi('显示了积分，就必须填写积分规则！','error');
		}
		if(!$post['card_id']){
			//创建卡券
			$wxcard=array('card'=>array(
				'card_type'=>'MEMBER_CARD',
				'member_card'=>array(
					'background_pic_url'=>$post['background_pic_url'],
					'prerogative'=>$post['prerogative'],
					'auto_activate'=>$post['auto_activate']?true:false,
					'supply_bonus'=>$post['supply_bonus']?true:false,
					'supply_balance'=>false,
					'activate_url'=>$post['wx_activate']?'':custom_url('core/member.wxcard/',true),
					'custom_field1'=>$post['custom_field'][0],
					'custom_field2'=>$post['custom_field'][1],
					'custom_field3'=>$post['custom_field'][2],
					'bonus_rules'=>$post['bonus_rules']?:'',
					'bonus_rule'=>array(
						'cost_money_unit'=>$post['cost_money_unit'],
						'increase_bonus'=>$post['increase_bonus'],
						'max_increase_bonus'=>$post['max_increase_bonus'],
						'init_increase_bonus'=>$post['init_increase_bonus'],
						'cost_bonus_unit'=>$post['cost_bonus_unit'],
						'reduce_money'=>$post['reduce_money'],
						'least_money_to_use_bonus'=>$post['least_money_to_use_bonus'],
						'max_reduce_bonus'=>$post['max_reduce_bonus'],
					),
					'discount'=>intval($post['discount']),
					'base_info'=>array(
						'logo_url'=>$post['logo_url'],
						'code_type'=>'CODE_TYPE_TEXT',
						'brand_name'=>$post['brand_name'],
						'title'=>$post['title'],
						'color'=>$post['color']?:'Color010',
						'notice'=>$post['notice']?:'使用时向服务员出示此券',
						'service_phone'=>$post['service_phone'],
						'description'=>$post['description'],
						'sku'=>array(
							'quantity'=>intval($post['quantity']),
						),
						'date_info'=>array(
							'type'=>'DATE_TYPE_PERMANENT',
						),
						'get_limit'=>1,
						'can_give_friend'=>false,
					),
					'advanced_info'=>array(
						'business_service'=>str_array($post['business_service']),
					),
					'wx_activate'=>$post['wx_activate']?true:false,
					'wx_activate_after_submit'=>$post['wx_activate_after_submit']?true:false,
					'wx_activate_after_submit_url'=>$post['wx_activate_after_submit_url'],
				),
			));
			if($post['diy_cover']){
				$wxcard['card']['member_card']['custom_cell1']=array(
					'name'=>$post['cover_title'],
					'tips'=>$post['cover_help'],
					'url'=>$post['cover_url'],
				);
			}
			$api_url='https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={access_token}';
			//上传logo图片
			$logo=cfc('files')->local($wxcard['card']['member_card']['base_info']['logo_url']);
			$res=cfc('account')->request($api_url,array('buffer'=>'@'.$logo));
			$wxcard['card']['member_card']['base_info']['logo_url']=$res['url'];
			//上传背景图片
			if($wxcard['card']['member_card']['background_pic_url']){
				$image=cfc('files')->local($wxcard['card']['member_card']['background_pic_url']);
				$res=cfc('account')->request($api_url,array('buffer'=>'@'.$image));
				$wxcard['card']['member_card']['background_pic_url']=$res['url'];
			}
			$api_create_url='https://api.weixin.qq.com/card/create?access_token={access_token}';
			$wxcard=ijson_encode($wxcard);			
			$res=cfc('account')->request($api_create_url,$wxcard);
			$post['card_id']=$res['card_id'];
			$post['card_ewm']=custom_url('core/member.wxcard/',true);
			//设置开卡字段接口建议开发者 activate_url、auto_activate 和 wx_activate 只填写一项
			if($post['wx_activate']){
				$api_activate_userform='https://api.weixin.qq.com/card/membercard/activateuserform/set?access_token={access_token}';
				$forms=array(
					'card_id'=>$res['card_id'],
					'required_form'=>array(
						"common_field_id_list"=>array(
							"USER_FORM_INFO_FLAG_NAME",
						),
					),
					"optional_form"=>array(
						"common_field_id_list"=>array(
							"USER_FORM_INFO_FLAG_MOBILE",
							"USER_FORM_INFO_FLAG_SEX",
						),
					)
				);
				$forms=ijson_encode($forms);	
				$res=cfc('account')->request($api_activate_userform,$forms);
			}
		}else{
			//编辑卡券
			$wxcard=array(
				'card_id'=>$post['card_id'],
				'member_card'=>array(
					'background_pic_url'=>$post['background_pic_url'],
					'prerogative'=>$post['prerogative'],
					'auto_activate'=>$post['auto_activate']?true:false,
					'supply_bonus'=>$post['supply_bonus']?true:false,
					'supply_balance'=>false,
					'activate_url'=>$post['wx_activate']?'':custom_url('core/member.wxcard/',true),
					'custom_field1'=>$post['custom_field'][0]?:array(),
					'custom_field2'=>$post['custom_field'][1]?:array(),
					'custom_field3'=>$post['custom_field'][0]?:array(),
					'bonus_rules'=>$post['bonus_rules']?:'',
					//'cost_money_unit'=>intval($post['cost_money_unit']),
					//'increase_bonus'=>intval($post['increase_bonus']),
					//'max_increase_bonus'=>intval($post['max_increase_bonus']),
					//'init_increase_bonus'=>intval($post['init_increase_bonus']),
					//'cost_bonus_unit'=>intval($post['cost_bonus_unit']),
					//'reduce_money'=>intval($post['reduce_money']),
					//'least_money_to_use_bonus'=>intval($post['least_money_to_use_bonus']),
					//'max_reduce_bonus'=>intval($post['max_reduce_bonus']),
					'discount'=>intval($post['discount']),
					'base_info'=>array(
						'logo_url'=>$post['logo_url'],
						'title'=>$post['title'],
						'color'=>$post['color']?:'Color010',
						'notice'=>$post['notice']?:'使用时向服务员出示此券',
						'service_phone'=>$post['service_phone'],
						'description'=>$post['description'],
						'date_info'=>array(
							'type'=>'DATE_TYPE_PERMANENT',
						),
						'get_limit'=>1,
						'can_give_friend'=>false,
					),
					'wx_activate'=>$post['wx_activate']?true:false,
					'wx_activate_after_submit'=>$post['wx_activate_after_submit']?true:false,
					'wx_activate_after_submit_url'=>$post['wx_activate_after_submit_url'],
				),
			);
			if($post['diy_cover']){
				$wxcard['member_card']['custom_cell1']=array(
					'name'=>$post['cover_title'],
					'tips'=>$post['cover_help'],
					'url'=>$post['cover_url'],
				);
			}
			$api_url='https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={access_token}';
			//上传logo图片
			$logo=cfc('files')->local($wxcard['member_card']['base_info']['logo_url']);
			$res=cfc('account')->request($api_url,array('buffer'=>'@'.$logo));
			$wxcard['member_card']['base_info']['logo_url']=$res['url'];
			//上传背景图片
			if($wxcard['member_card']['background_pic_url']){
				$image=cfc('files')->local($wxcard['member_card']['background_pic_url']);
				$res=cfc('account')->request($api_url,array('buffer'=>'@'.$image));
				$wxcard['member_card']['background_pic_url']=$res['url'];
			}
			$wxcard=ijson_encode($wxcard);
			$api_update_url='https://api.weixin.qq.com/card/update?access_token={access_token}';
			$res=cfc('account')->request($api_update_url,$wxcard);
			$post['card_ewm']=custom_url('core/member.wxcard/',true);
		}
		uni_setting('wx_card_edit',$post);
		exi('设置成功！');
	}
	$setting=uni_setting('wx_card_edit');
	$setting['custom_field']=$setting['custom_field']?:array();
	if($setting['card_id']){
		//获取当前卡券库存
		$api_url='https://api.weixin.qq.com/card/get?access_token={access_token}';
		$params=array('card_id'=>$setting['card_id']);
		$params=ijson_encode($params);
		$res=cfc('account')->request($api_url,$params,'','',true);
		if($res['card'] && $res['card']['member_card']){
			$setting['quantity']=$res['card']['member_card']['base_info']['sku']['quantity'];
			$statuss=array(
				'CARD_STATUS_NOT_VERIFY'=>0,
				'CARD_STATUS_VERIFY_OK'=>1,
				'CARD_STATUS_VERIFY_FAIL'=>2,
				'CARD_STATUS_DELETE'=>3,
				'CARD_STATUS_DISPATCH'=>4,
			);
			$setting['status']=$statuss[$res['card']['member_card']['base_info']['status']];
			uni_setting('wx_card_edit',$setting);
		}
	}
	if(!$setting['card_id']){
		$setting['card_id']='';
	}
	$return['item']=$setting;
	$return['statuss']=array(
		'0'=>'待审核',
		'1'=>'审核通过',
		'2'=>'审核失败',
		'3'=>'卡券被商户删除',
		'4'=>'在公众平台投放过的卡券',
	);
	if($return['item']['card_id']){
		$read=true;
	}else{
		$read=false;
	}
	$return['backs']=array(
		'1'=>'背景颜色',
		'2'=>'背景图片',
	);
	$return['services']=array(
		'BIZ_SERVICE_FREE_WIFI'=>'免费WIFI',
		'BIZ_SERVICE_DELIVER'=>'外卖服务',
		'BIZ_SERVICE_FREE_PARK'=>'停车位',
		'BIZ_SERVICE_WITH_PET'=>'可带宠物',
	);
	$htmls[]=array(
		'type'=>'look',
		'width'=>'350px',
		'flex'=>1,
		'look'=>array(
				array('type'=>'membercard'),
			),
	);
	$htmls[]=array(
		'type'=>'edit',
		'edit'=>array(
			array('type'=>'tip','title'=>'[温馨提示]：<red>微信会员卡的领取，必须配置好《微信公众号token验证》---微信公众号后台--开发--基本配置--服务器配置（绑定并启用）</red>；否则会无法激活会员卡！对于已经领取了，无法激活的用户，可以点右键，删除会员卡，重新领取！'),
			array('type'=>'string','name'=>'title','title'=>'会员卡标题','help'=>''),
			array('type'=>'string','name'=>'brand_name','title'=>'商户名称','help'=>'创建后不能修改','read'=>$read),
			array('type'=>'string','name'=>'quantity','title'=>'当前库存','help'=>'','read'=>$read),
			array('type'=>'radio','name'=>'status','title'=>'会员卡状态','options'=>'statuss','show'=>array('card_id !='=>''),'read'=>$read,'help'=>'显示会员卡状态，不可编辑！'),
			array('type'=>'switch','name'=>'auto_activate','title'=>'会员卡需要激活？','help'=>'激活会员卡时是否需要填写激活信息,不需求则自动激活会员卡！'),
			array('type'=>'ewm','name'=>'card_ewm','title'=>'领卡二维码','help'=>'可以扫码测试领取微信会员卡，也可直接点击右键下载二维码图片'),
			array('type'=>'image','name'=>'logo_url','title'=>'logo图片','help'=>'上传的logo图片限制文件大小限制1MB，像素为300*300，仅支持JPG、PNG格式。'),
			array('type'=>'switch','name'=>'supply_bonus','title'=>'是否显示积分','read'=>$read,'help'=>'若开启，则后续不可以被关闭，使用微信卡券积分（具体为在会员卡中使用“积分/supply_balance”字段）需提交《单用途预付卡备案》。 操作指引详见： <a href="https://mp.weixin.qq.com/cgi-bin/readtemplate?token=1091016770&t=cardticket/faq_tmpl&type=info&token=1494071418&lang=zh_CN#3dot2" target="_blank">卡券储值功能权限开通。</a>​'),
			//array('type'=>'radio','name'=>'background_type','title'=>'会员卡背景','options'=>'backs','help'=>''),
			//array('type'=>'radio','name'=>'color','title'=>'卡颜色','options'=>'colors'),
			array('type'=>'image','name'=>'background_pic_url','title'=>'背景图片','help'=>'建议像素为1000*600。图片大小不能超过1mb,仅支持jpg,png格式'),
			array('type'=>'string','name'=>'notice','title'=>'使用提醒','help'=>'默认：使用时向服务员出示此券'),
			array('type'=>'string','name'=>'service_phone','title'=>'客服电话','help'=>''),
			array('type'=>'text','name'=>'prerogative','title'=>'特权说明','help'=>''),
			array('type'=>'text','name'=>'description','title'=>'使用须知','help'=>''),
			array('type'=>'checkbox','name'=>'business_service','title'=>'商户服务','options'=>'services','help'=>'商户服务在会员卡创建成功后无法修改！','read'=>$read),
			array('type'=>'switch','name'=>'diy_cover','title'=>'显示自定义入口'),
			array('type'=>'string','name'=>'cover_title','title'=>'入口名称','help'=>'','show'=>array('diy_cover'=>1)),
			array('type'=>'string','name'=>'cover_help','title'=>'引导语','help'=>'','show'=>array('diy_cover'=>1)),
			array('type'=>'link','name'=>'cover_url','title'=>'跳转地址','help'=>'','show'=>array('diy_cover'=>1)),
			array('type'=>'array','title'=>'自定义消息类目','name'=>'custom_field','add_tip'=>'添加一个类目',
								'list'=>array(
									array('type'=>'radio','name'=>'name_type','title'=>'系统名称','options'=>'name_types'),	
									array('type'=>'string','name'=>'name','title'=>'自定义名'),
									array('type'=>'string','name'=>'url','title'=>'地址'),
								),
								'details'=>array(
									array('type'=>'radio','name'=>'name_type','title'=>'系统名称','options'=>'name_types'),
									array('type'=>'string','name'=>'name','title'=>'自定义名','help'=>'如果是选用系统名称，就可以不要设置自定义名！'),
									array('type'=>'link','name'=>'url','from'=>'action','title'=>'地址'),
								)
			),
			array('type'=>'switch','name'=>'wx_activate','title'=>'支持一键开卡','help'=>'开启后，调整激活链接将失效！'),
			array('type'=>'switch','name'=>'wx_activate_after_submit','title'=>'是否支持跳转型一键激活'),
			array('type'=>'link','name'=>'wx_activate_after_submit_url','title'=>'一键激活跳转的地址链接','help'=>'','show'=>array('wx_activate_after_submit'=>1)),			
			array('type'=>'text','name'=>'bonus_rules','title'=>'积分规则','help'=>''),
			array('type'=>'tip','title'=>'微信会员卡官方要求：<red>下面的积分相关设置，提交后不能再修改！请谨慎操作！</red>','help'=>''),
			array('type'=>'string_two','read'=>$read,'title'=>'消耗获得积分','unit1'=>'元','name1'=>'cost_money_unit','title1'=>'消费','unit2'=>'个积分','name2'=>'increase_bonus','title2'=>'增加','help'=>'消费多少金额。应增加多少积分。'),
			array('type'=>'unitstring','read'=>$read,'unit'=>'个','name'=>'max_increase_bonus','title'=>'用户单次可获取的积分上限','help'=>'用户单次可获取的积分上限。'),
			array('type'=>'unitstring','read'=>$read,'unit'=>'个','name'=>'init_increase_bonus','title'=>'初始设置积分','help'=>'初始设置积分。'),
			array('type'=>'string_two','read'=>$read,'title'=>'积分抵扣','unit1'=>'个积分','name1'=>'cost_bonus_unit','title1'=>'消耗','unit2'=>'元','name2'=>'reduce_money','title2'=>'抵扣','help'=>'每使用X积分抵扣多少元。'),
			array('type'=>'unitstring','read'=>$read,'unit'=>'个','name'=>'least_money_to_use_bonus','title'=>'抵扣条件，满xx元','help'=>'抵扣条件，满xx元（这里以分为单位）可用。'),
			array('type'=>'unitstring','read'=>$read,'unit'=>'个','name'=>'max_reduce_bonus','title'=>'抵扣条件','help'=>'抵扣条件，单笔最多使用xx积分。'),
			array('type'=>'string','name'=>'discount','title'=>'折扣','help'=>'该会员卡享受的折扣优惠,填10就是九折。'),
			array('type'=>'tip','title'=>'【温馨提示】：<red>下面关于小程序的设置，必须本公众号下面关联的小程序，才有效！且必须申请一个开放平台账号，并将小程序和公众号绑定在同一个开放平台账号下。</red>'),
			array('type'=>'string','name'=>'activate_app_brand_user_name','title'=>'跳转小程序账号','help'=>'示例：XXXxx@qq.com'),
			array('type'=>'string','name'=>'activate_app_brand_pass','title'=>'跳转小程序链接','help'=>'示例：/core/member/wxcard/index'),
		),
	);
	$return['htmls']=$htmls;
	exi($return);
}
if($_RQ['op']=='change'){
	//修改库存
	$setting=uni_setting('wx_card_edit');
	if($_RQ['postdata']){
		$post=get_postdata();
		$update_api_url='https://api.weixin.qq.com/card/modifystock?access_token={access_token}';
		$params=array(
			'card_id'=>$post['card_id'],
		);
		if($post['type']==1){
			$params['increase_stock_value']=intval($post['value']);
			$setting['quantity']=$post['quantity']+$params['increase_stock_value'];
		}else{
			$params['reduce_stock_value']=intval($post['value']);
			$setting['quantity']=$post['quantity']-$params['reduce_stock_value'];
			if($setting['quantity']<0){
				exi('库存不足！','error');
			}
		}
		uni_setting('wx_card_edit',$setting);
		$params=ijson_encode($params);
		$res=cfc('account')->request($update_api_url,$params);
		exi('操作成功！','','edit');
	}
	
	if(!$setting || !$setting['card_id']){
		exi('请先创建会员卡！','error','edit');
	}
	//查询库存
	$api_url='https://api.weixin.qq.com/card/get?access_token={access_token}';
	$params=array('card_id'=>$setting['card_id']);
	$params=ijson_encode($params);
	$res=cfc('account')->request($api_url,$params);
	
	$return['item']=array(
		'card_id'=>$setting['card_id'],
		'quantity'=>$res['card']['member_card']['base_info']['sku']['quantity'],
		'total_quantity'=>$res['card']['member_card']['base_info']['sku']['total_quantity'],
		
	);
	$return['htmls']=array(
		'type'=>'edit',
		'edit'=>array(
			array('type'=>'string','name'=>'total_quantity','title'=>'会员卡总数','help'=>'','read'=>true),
			array('type'=>'string','name'=>'quantity','title'=>'当前剩余','help'=>'','read'=>true),
			array('type'=>'radio','name'=>'type','title'=>'修改方式','options'=>'types'),
			array('type'=>'string','name'=>'value','title'=>'增加/减少数量','help'=>'填写添加或减少库存数量'),
		),
	);
	$return['types']=array(
		'1'=>'增加库存',
		'2'=>'减少库存',
	);
	exi($return);
}
if($_RQ['op']=='del'){
	//删除会员卡
	 confirm('删除后，所有已领取的会员卡将会全部失效，确定删除吗？','del_card','edit');
}
if($_RQ['op']=='del_card'){
	//执行删除会员卡操作
	$delete_api_url='https://api.weixin.qq.com/card/delete?access_token={access_token}';
	$setting=uni_setting('wx_card_edit');
	if(!$setting['card_id']){
		exi('您尚未创建会员卡，无需删除！','error','edit');
	}
	$params=array(
		'card_id'=>$setting['card_id'],
	);
	$params=ijson_encode($params);
	$res=cfc('account')->request($delete_api_url,$params);
	uni_setting('wx_card_edit',array());
	exi('删除成功！','','edit');
}